import pyglet
from pyglet.gui import PushButton
from pyglet.image import SolidColorImagePattern
from pyglet.window import key
import os
import PIL

from BaseScene import BaseScene
from tranlator import my_translator


class GameScene(BaseScene):
    """游戏场景"""
    def __init__(self, scene_manager,pointer):
        super().__init__(scene_manager)





        # 创建游戏界面元素
        # self.background = shapes.Rectangle(0, 0, self.window.width, self.window.height,
        #                                    color=(30, 30, 100), batch=self.batch)
        # self.text = pyglet.text.Label('游戏进行中... 按ESC返回主菜单', font_name='SimHei', font_size=20,
        #                               x=self.window.width // 2, y=self.window.height // 2,
        #                               anchor_x='center', batch=self.batch)
        # background_sprite
        # background_preparing_sprite#开始是为透明，为背景切换做准备
        # people_sprite#人物立绘
        # text  box#文本框
        # juqin_label#放剧情文字
        # ############游戏主代码
        # #以读取脚本作为主线程
        # btn_nxt
        # set btn_nxt handler(btnxt_handerler)
        #self.background_sprite=pyglet.sprite.Sprite(self.pic_resources["gamebg"], batch=self.batch,group=self.group0)
        #self.character_sprite=pyglet.sprite.Sprite(self.pic_resources["gamebg"], batch=self.batch,group=self.group1)
        self.textbox = pyglet.sprite.Sprite(self.pic_resources["textbox"], x=int((self.window.width - 1920) / 2),y=int((self.window.height - 1080) / 2), batch=self.batch,group=self.group2)
        self.dialog_box = pyglet.text.Label(
            text="",
            font_size=20,
            font_name='SimHei',
            x=100,
            y=200,
            width=100,
            multiline=True,
            align="left",
            batch=self.batch,
            group=self.group2
        )
        # 对话文本的索引（当前到哪一个字符）
        self.dialog_box_text_index: int = 0
        # 待显示的对话文本
        self.dialog_box_text_to_show: str = ""


        dim1 = SolidColorImagePattern((100, 226, 253, 255)).create_image(200, 50)
        pim1 = SolidColorImagePattern((255, 0, 0, 255)).create_image(200, 50)
        #self.btnxt = PushButton(x=1000, y=300, pressed=pim1,unpressed=dim1,batch=self.batch,group=self.group3)
        self.bt_save = PushButton(self.scene_manager.get_cx()+1700, self.scene_manager.get_cy()+400, self.pic_resources["msaves1"], self.pic_resources["msaves0"],self.pic_resources["msaves2"],batch=self.batch,group=self.group3)
        #self.btnxt.set_handler('on_release',self.btnxt_handerler)
        self.bt_save.set_handler('on_release', self.bt_save_handerler)
        #self.buttons.append(self.btnxt)
        self.buttons.append(self.bt_save)



        self.pointer = pointer

        self.trans = my_translator()
        self.trans.compile_scripts()


        self.charactor_dict={}

        self.first_time_use = 1

        self.update_handerler()

    def on_mouse_press(self, x, y, button, modifiers):
        """处理鼠标点击"""
        if button == pyglet.window.mouse.LEFT:
            if (self.textbox.x <= x <= self.textbox.x + self.textbox.width and self.textbox.y <= y <= self.textbox.y + self.textbox.height):
                self.btnxt_handerler(None)
                return True  # 事件已处理
        return False

    def update_handerler(self):
        current_command=self.trans.sorted_commands[self.pointer]

        # 下面防止从存档加载时背景人物音乐都没有的情况   emm可能还有pause的问题解决 emm还有进来时文字命令的问题解决
        # 总之第一次加载情况还蛮多的

        if self.first_time_use==1:
            flag = False
            point1=self.pointer
            while True:
                #print(self.trans.sorted_commands)
                for cmd0 in self.trans.sorted_commands[point1][1]:
                    if cmd0[0]=='bg':
                        #print("yes")
                        if point1!=self.pointer:
                            current_command[1].append(cmd0)
                        flag=True
                        break
                if flag:
                    break
                point1-=1

            point1 = self.pointer
            while point1>=0:
                #print(self.trans.sorted_commands)
                for cmd0 in self.trans.sorted_commands[point1][1]:
                    #print("cmd0:")
                    #print(cmd0)
                    if cmd0[0] == 'muc' or cmd0[0]=='voice':
                        #print("yes")
                        if cmd0[1]== 'play' or cmd0[1]== 'pause':
                            name = cmd0[2]
                            nflag=True
                            for i in range(point1,self.pointer+1):
                                for cmdchara in self.trans.sorted_commands[i][1]:
                                    if (cmdchara[0] == 'muc' or cmdchara[0]=='voice') and cmdchara[1] == 'remove' and cmdchara[2] == name:
                                        nflag=False#判断之前创建的人物立绘之后有没有删掉，如果没删掉那么在fist time use里就该出现
                            if point1 != self.pointer and nflag==True:
                                current_command[1].append(cmd0)
                point1 -= 1
            point1 = self.pointer
            while point1>=0:
                #print(self.trans.sorted_commands)
                for cmd0 in self.trans.sorted_commands[point1][1]:
                    #print("cmd0:")
                    #print(cmd0)
                    if cmd0[0] == 'chara':
                        #print("yes")
                        if cmd0[1]== 'add':
                            name = cmd0[2]
                            nflag=True
                            for i in range(point1,self.pointer+1):
                                for cmdchara in self.trans.sorted_commands[i][1]:
                                    if cmdchara[0] == 'chara' and cmdchara[1] == 'remove' and cmdchara[2] == name:
                                        nflag=False#判断之前创建的人物立绘之后有没有删掉，如果没删掉那么在fist time use里就该出现
                            if point1 != self.pointer and nflag==True:
                                current_command[1].append(cmd0)
                point1 -= 1
            print(current_command)
        self.first_time_use=0

        #执行cmd_block
        for cmd in current_command[1]:
            if cmd[0]=='bg':
                #self.background_sprite = pyglet.sprite.Sprite(self.pic_resources[cmd[]], batch=self.batch,group=self.group0)
                self.fade_in_picture(self.pic_resources[cmd[2]],1)
            if cmd[0]=='chara':
                if cmd[1]=='add':
                    self.charactor_dict[cmd[2]]=pyglet.sprite.Sprite(self.characor_pic_resources[cmd[2]],x=int(cmd[3]),y=100,batch=self.batch,group=self.group1)
                if cmd[1]=='remove':
                    try:
                        self.charactor_dict[cmd[2]].delete()
                    except:
                        pass
            if cmd[0] == 'muc' or cmd[0]=='voice':
                if cmd[1]=='play' or cmd[1]=='add':
                    if len(cmd)==4:
                        if cmd[3]=='loop':
                            self.play_music(cmd[2])
                    else:
                        self.play_music(cmd[2],loop=False)
                elif cmd[1]=='pause':
                    print("pause")
                    try:
                        self.pause_music(cmd[2])
                    except:
                        pass
                elif cmd[1]=='remove':
                    try:
                        self.delete_music(cmd[2])
                    except:
                        pass


        #执行文字命令
        texttt=current_command[2]
        wrapped_text = "\n".join([texttt[i:i + 45] for i in range(0, len(texttt), 45)])

        # self.dialog_box.text = wrapped_text
        # 显示对话的文本
        self.show_text_char_by_char(wrapped_text)

    def show_text_char_by_char(self, complete_text: str):
        """逐个字地添加文本，即打字效果"""
        # 停下未完成的文本任务（如果前一个已经完成则该函数默认忽略）
        pyglet.clock.unschedule(self.show_text_char_by_char_step)
        # 重置文本指针位置
        self.dialog_box_text_index = 0
        self.dialog_box.text = ""
        # 保存完整文本
        self.dialog_box_text_to_show = complete_text
        # 0.5秒内显示完毕
        pyglet.clock.schedule_interval_soft(self.show_text_char_by_char_step, 0.5 / len(complete_text))

    def show_text_char_by_char_step(self, dt):
        """执行一步文本更新"""
        if self.dialog_box_text_index < len(self.dialog_box_text_to_show):
            self.dialog_box.text = self.dialog_box.text + self.dialog_box_text_to_show[self.dialog_box_text_index]
            self.dialog_box_text_index += 1
        else:
            pyglet.clock.unschedule(self.show_text_char_by_char_step)

    def btnxt_handerler(self,button):
        print("pressed btnxt")
        self.pointer += 1
        self.update_handerler()

    def bt_save_handerler(self,button):
        #threading.Thread(target=self.MakeScreenshot).start()
        pyglet.clock.schedule_once(self.MakeScreenshot, 0)
        # save_scene = SaveScene(self.scene_manager,self.pointer)
        print("pressed btnxt")
        self.scene_manager.switch_scene("save", self.pointer)

    def on_draw(self):
        """绘制游戏场景"""
        self.window.clear()
        self.batch.draw()

    def on_key_press(self, symbol, modifiers):
        """键盘事件处理"""
        if symbol == key.ESCAPE:
            # 返回开始场景
            # start_scene = StartScene(self.scene_manager)
            self.scene_manager.switch_scene("start")

    def MakeScreenshot(self,dt):
        screenshot = pyglet.image.get_buffer_manager().get_color_buffer()
        screenshot.save("saves\screenshot_tmp.png")
        image = PIL.Image.open("saves\screenshot_tmp.png")
        resized_image = image.resize((192,108))
        resized_image.save("saves\screenshot_tmp_ok.png")
        os.remove("saves\screenshot_tmp.png")
